package java44th.group.service.wx.coupon;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import java44th.group.bean.admin.vo.admin.ListVo;
import java44th.group.bean.po.MarketCoupon;
import java44th.group.bean.po.MarketCouponUser;
import java44th.group.bean.wx.bo.coupon.TimeData;
import java44th.group.bean.wx.bo.coupon.CodeBo;
import java44th.group.bean.wx.bo.coupon.CouponId;
import java44th.group.bean.wx.vo.coupon.CodeVO;
import java44th.group.bean.wx.vo.coupon.CouponsListVo;
import java44th.group.bean.wx.vo.coupon.CouponsUserListVo;
import java44th.group.bean.wx.vo.coupon.CouponsUserVo;
import java44th.group.mapper.MarketCouponMapper;
import java44th.group.mapper.MarketCouponUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

/**
 * @Aurhor: 王可龙
 * @DATE: 2022/10/15 14:50
 * @Package:java44th.group.service.wx.coupon
 * @Description:
 * @Version 1.0
 */
@Service
public class MarketCouponServiceImpl implements MarketCouponService {

    @Autowired
    MarketCouponMapper marketCouponMapper;

    @Autowired
    MarketCouponUserMapper marketCouponUserMapper;


    @Override
    public ListVo list(Integer page, Integer limit) {

        // 更新优惠卷的状态码
        updateAllCoupon();


        PageHelper.startPage(page, limit);

        // MarketCouponExample marketCouponExample = new MarketCouponExample();
        // List<MarketCoupon> marketCoupons = marketCouponMapper.selectByExample(marketCouponExample);

        List<MarketCoupon> marketCoupons = marketCouponMapper.selectByStstus();

        PageInfo<MarketCoupon> marketCouponPageInfo = new PageInfo<>(marketCoupons);

        LinkedList<CouponsListVo> couponsListVos = new LinkedList<>();
        for (MarketCoupon marketCoupon : marketCoupons) {
            String startTime = "";
            String endtTime = "";
            if (marketCoupon.getStartTime() != null) {
                startTime = marketCoupon.getStartTime().toString();
            }
            if (marketCoupon.getEndTime() != null) {
                endtTime = marketCoupon.getEndTime().toString();
            }
            CouponsListVo couponsListVo = new CouponsListVo(marketCoupon.getId(), marketCoupon.getName(), marketCoupon.getDesc(),
                    marketCoupon.getTag(), marketCoupon.getDiscount(), marketCoupon.getMin(), marketCoupon.getDays().intValue());
            couponsListVos.add(couponsListVo);
        }


        Integer total = (Integer) Math.toIntExact(marketCouponMapper.selectByStstusCount());
        Integer pages = total / limit;
        if (total % limit > 0) {
            pages++;
        }

        ListVo listVo = new ListVo(total, pages, limit, page, couponsListVos);
        return listVo;
    }


    @Override
    public ListVo myList(Integer id, Integer status, Integer page, Integer limit) {
        MarketCouponUser marketCouponUser = new MarketCouponUser();
        marketCouponUser.setStatus(status.shortValue());
        marketCouponUser.setUserId(id);

        PageHelper.startPage(page, limit);


        LinkedList<CouponsUserListVo> couponsUserListVo = marketCouponUserMapper.selectCouponUserByStatus(marketCouponUser);

        // PageInfo<CouponsUserListVo> marketCouponPageInfo = new PageInfo<>(couponsUserListVo);

        LinkedList<CouponsUserVo> linkedList = new LinkedList<>();
        for (CouponsUserListVo u : couponsUserListVo) {
            CouponsUserVo couponsUserVo = new CouponsUserVo(u.getId(), u.getCid(),
                    u.getName(), u.getDesc(), u.getTag(), u.getMin(), u.getDiscount(),
                    u.getStartTime().toString(), u.getEndTime().toString(), false);
            linkedList.add(couponsUserVo);
        }
        Integer total = Math.toIntExact(marketCouponUserMapper.countByUserIdAndStatus(id, status));
        Integer pages = total / limit;
        if (total % limit > 0) {
            pages++;
        }

        ListVo listVo = new ListVo(total, pages, limit, page, linkedList);
        return listVo;
    }

    @Override
    public Integer receive(Integer userId, CouponId couponId) throws ParseException {

        MarketCoupon marketCoupon = marketCouponMapper.selectByPrimaryKey(couponId.getCouponId());
        Integer integer = marketCouponUserMapper.selectUserCouponCountByCouponId(couponId.getCouponId());
        //控制每人只能领取多少、控制优惠券数量
        if (marketCoupon.getTotal()<=0 || integer.shortValue()>marketCoupon.getLimit()){
            return 1;
        }
        if (marketCoupon.getEndTime()!=null) {
            Date date = new Date();
            System.out.println();
            MarketCouponUser marketCouponUser = new MarketCouponUser(null, userId, couponId.getCouponId(),
                    null, null, marketCoupon.getStartTime(), marketCoupon.getEndTime(),
                    null, new Timestamp(date.getTime()), null, false);
            int i = marketCouponUserMapper.insertSelective(marketCouponUser);
            return 0;
        }
        Date date = new Date();
        Calendar calendar2 = Calendar.getInstance();
        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        calendar2.add(Calendar.DATE, marketCoupon.getDays());
        String endTimeString = sdf2.format(calendar2.getTime());
        Date endTime = sdf2.parse(endTimeString);
        MarketCouponUser marketCouponUser = new MarketCouponUser(null, userId, couponId.getCouponId(),
                null, null, new Timestamp(System.currentTimeMillis()), endTime,
                null, new Timestamp(date.getTime()), null, false);
        int i = marketCouponUserMapper.insertSelective(marketCouponUser);
        // 优惠卷数量减一
        MarketCoupon marketCoupon1 = new MarketCoupon();
        marketCoupon1.setId(couponId.getCouponId());
        marketCoupon1.setTotal(marketCoupon.getTotal()-1);
        int i1 = marketCouponMapper.updateByPrimaryKeySelective(marketCoupon1);
        // 更新所有优惠卷状态信息
        updateAllCoupon();
        return 0;
    }

    @Override
    public ListVo selectlist(Integer id) {
        MarketCouponUser marketCouponUser = new MarketCouponUser();
        //可用的优惠卷
        Integer status = 0;
        marketCouponUser.setStatus(status.shortValue());
        marketCouponUser.setUserId(id);


        LinkedList<CouponsUserListVo> couponsUserListVo = marketCouponUserMapper.selectCouponUserByStatus(marketCouponUser);


        LinkedList<CouponsUserVo> linkedList = new LinkedList<>();
        for (CouponsUserListVo u : couponsUserListVo) {
            String startTime = "";
            String endtTime = "";
            if (u.getStartTime() != null) {
                startTime = u.getStartTime().toString();
            }
            if (u.getEndTime() != null) {
                endtTime = u.getEndTime().toString();
            }
            CouponsUserVo couponsUserVo = new CouponsUserVo(u.getId(), u.getCid(),
                    u.getName(), u.getDesc(), u.getTag(), u.getMin(), u.getDiscount(),
                    startTime, endtTime, true);
            linkedList.add(couponsUserVo);
        }
        Integer total = Math.toIntExact(marketCouponUserMapper.countByUserIdAndStatus(id, status));
        ListVo listVo = new ListVo(total, 1, total, 1, linkedList);
        return listVo;

    }

    @Override
    public Integer exchange(Integer userId, CodeBo codeBo) throws ParseException {
        //查找状态为可用的兑换码优惠卷的兑换码
        LinkedList<CodeVO> codeVOS = marketCouponMapper.selectCodeByUserId();
        for (CodeVO codeVO : codeVOS) {
            if (codeBo.getCode().equals(codeVO.getCode())) {
                CouponId couponId = new CouponId();
                couponId.setCouponId(codeVO.getId());
                receive(userId, couponId);
                return 1;
            }
        }
        return 0;
    }

    /**
     * 更新用户优惠卷的状态
     *
     * @param userId
     */
    @Override
    public void updateStatusByUserId(Integer userId) {
        LinkedList<TimeData> times = marketCouponUserMapper.selectByUserId(userId);
        MarketCouponUser marketCouponUser = new MarketCouponUser();
        for (TimeData time : times) {
            // 优惠卷过期
            long a = time.getEndTime().getTime();
            //当前时间
            Timestamp timestamp = new Timestamp(System.currentTimeMillis());
            long b = timestamp.getTime();
            if (b > a) {
                Integer status = 2;
                marketCouponUser.setStatus(status.shortValue());
                marketCouponUser.setId(time.getId());
                int i = marketCouponUserMapper.updateByPrimaryKeySelective2(marketCouponUser);
            }
        }
    }

    /**
     * 更新所有优惠卷的状态
     */
    private void updateAllCoupon() {
        List<MarketCoupon> marketCoupons = marketCouponMapper.selectByExample(null);
        for (MarketCoupon marketCoupon : marketCoupons) {
            MarketCoupon marketCoupon1 = new MarketCoupon();
            if (marketCoupon.getEndTime()!=null) {
                long endTime = marketCoupon.getEndTime().getTime();
                Timestamp timestamp = new Timestamp(System.currentTimeMillis());
                long currentTime = timestamp.getTime();
                if (currentTime > endTime) {
                    Integer status = 1;
                    marketCoupon1.setStatus(status.shortValue());
                    marketCoupon1.setId(marketCoupon.getId());
                    int i = marketCouponMapper.updateByPrimaryKeySelective(marketCoupon1);
                    continue;
                }
            }
            if (marketCoupon.getTotal() <= 0) {
                Integer status = 2;
                marketCoupon1.setStatus(status.shortValue());
                marketCoupon1.setId(marketCoupon.getId());
                int i = marketCouponMapper.updateByPrimaryKeySelective(marketCoupon1);
                continue;
            }
        }
    }

}
